Skip to content

Latest commit

 

History

History
75 lines (59 loc) · 1.68 KB

File metadata and controls

75 lines (59 loc) · 1.68 KB

1329. Sort the Matrix Diagonally

Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array.

Example 1:

Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • 1 <= mat[i][j] <= 100

Solutions (Ruby)

1. Solution

# @param {Integer[][]} mat# @return {Integer[][]}defdiagonal_sort(mat)m,n=mat.length,mat[0].lengthforiin0...(m + n)row=[m - 1 - i,0].maxcol=[i - m + 1,0].maxarr=[]forjin0...[m - row,n - col].minarr.push(mat[row + j][col + j])endarr.sort!forjin0...[m - row,n - col].minmat[row + j][col + j]=arr[j]endendreturnmatend

Solutions (Rust)

1. Solution

implSolution{pubfndiagonal_sort(mat:Vec<Vec<i32>>) -> Vec<Vec<i32>>{let m = mat.len();let n = mat[0].len();letmut ret = vec![vec![0; n]; m];for i in0..(m + n){letmut row = (m - 1).saturating_sub(i);letmut col = i.saturating_sub(m - 1);letmut arr = vec![];for j in0..(m - row).min(n - col){ arr.push(mat[row + j][col + j]);} arr.sort_unstable();for j in0..(m - row).min(n - col){ ret[row + j][col + j] = arr[j];}} ret }}
close